import pymysql


class DBUtil:
    conn = None

    # 封装数据库创建conn
    @classmethod
    def __connect_db(cls):
        cls.conn = pymysql.connect(host="211.103.136.244", port=7061, user="student", password="iHRM_student_2021",
                                   database="ihrm", charset="utf8")
        return cls.conn
        pass

    # 封装数据库关闭close
    @classmethod
    def __close_db(cls):
        cls.conn.close()
        pass

    # 查询方法
    @classmethod
    def select_one(cls, sql):
        result = None
        cursor = None
        try:
            # 创建连接conn
            cls.conn = cls.__connect_db()
            # 获得游标cursor
            cursor = cls.conn.cursor()
            # 执行查询语句，获取结果，并且返回结果
            cursor.execute(sql)
            result = cursor.fetchone()
        except Exception as err:
            print("查询数据库错误：", str(err))
        finally:
            # 关闭游标cursor
            cursor.close()

            # 关闭连接conn
            cls.__close_db()
            # 最后返回结果出来
            return result

    # 增删改查方法
    @classmethod
    def uid_db(cls, sql):
        cursor = None
        try:
            # 创建连接conn
            cls.conn = cls.__connect_db()
            # 获得游标cursor
            cursor = cls.conn.cursor()
            # 执行增删改语句，打印影响行数
            cursor.execute(sql)
            affect_rows = cls.conn.affected_rows()
            print("影响的行数=", affect_rows)
            # 事务的提交，回滚
            cls.conn.commit()
        except Exception as err:
            print("增删改数据库报错=", str(err))
            # 事物的回滚
            cls.conn.rollback()
        finally:
            # 关闭游标cursor
            cursor.close()
            # 关闭连接conn
            cls.__close_db()


if __name__ == '__main__':
    # result = DBUtil.select_one("SELECT * FROM t_book;")
    # print("result=",result)
    DBUtil.uid_db("UPDATE t_book set title='三国志' WHERE id=5;")